/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.brucexx.wedding.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author zx04741
 */
public class AES {
    // 加密

  /**
         * 对数据用AES算法加密
         * @param plainText  要加密的字节数组
         * @param key  密钥
         * @return 加密后的字节数组
         */
        private static byte [] encrypt(byte [] plainText, byte [] key) {
            try{
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] decryptText = cipher.doFinal(plainText);
            return decryptText;
             } catch(Exception e) {
                 e.printStackTrace();
                 return null;
             }
        }

/**
         * 对AES算法加密的数据解密
         * @param cipherText  要解密的字节数组
         * @param key  密钥
         * @return 解密后的字节数组
         */
         private static byte [] decrypt(byte [] cipherText, byte [] key) {
            try{
                SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
                Cipher cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
                byte[] plainText = cipher.doFinal(cipherText);
                return plainText;
             } catch(Exception e) {
                 e.printStackTrace();
                 return null;
             }
         }



    public static void main(String[] args) throws Exception {
        byte[] key="hello".getBytes();
        String txt="mydarling";
        byte[] encode=encrypt(txt.getBytes(), key);
        byte[] decode=decrypt(encode, key);
        System.out.println(new String(decode));
    }
}
